package cn.wzc.crystal.platform.i18n.config;

import cn.wzc.crystal.platform.i18n.I18nProvider;
import cn.wzc.crystal.platform.i18n.I18nService;
import cn.wzc.crystal.platform.i18n.impl.CacheableI18nProvider;
import cn.wzc.crystal.platform.i18n.impl.I18nMessageSource;
import cn.wzc.crystal.platform.i18n.impl.JdbcI18nProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
@RequiredArgsConstructor
public class I18nConfigure {

	private final I18nProperties i18nProperties;


	/**
	 * 数据库国际化
	 *
	 * @param jdbcTemplate jdbc 末班
	 * @return 从数据库读取的消息源
	 */
	private MessageSource jdbcMessageSource(JdbcTemplate jdbcTemplate) {
		I18nProvider i18nProvider;

		i18nProvider = new JdbcI18nProvider(jdbcTemplate);

		// 开启缓存
		if (i18nProperties.isCacheable()) {
			i18nProvider = new CacheableI18nProvider(i18nProvider);
		}

		final I18nMessageSource i18nMessageSource = new I18nMessageSource(i18nProvider);
		i18nMessageSource.setDefaultLocale(i18nProperties.getDefaultLocale());
		return i18nMessageSource;
	}

	@Bean
	public I18nService i18nService(JdbcTemplate jdbcTemplate, MessageSource messageSource) {
		if (i18nProperties.getProvider() == I18nProperties.Provider.dataBase) {
			return new I18nService(jdbcMessageSource(jdbcTemplate));
		} else {
			return new I18nService(messageSource);
		}
	}


}
